package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {

        // 验证手机号码
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if(phoneInvalid) {
            return Result.fail("手机号错误");
        }
        // 6位随机码
        String code = RandomUtil.randomNumbers(6);
        // 放到session
        // session.setAttribute("code", code);
        // 放到redis
        stringRedisTemplate.opsForValue().set("login:code:" + phone, code, 2, TimeUnit.MINUTES);
        log.info("验证码：{}", code);

        // 直接返回
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1、校验手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(loginForm.getPhone());
        if(phoneInvalid) {
            return Result.fail("手机号错误");
        }

        // 2、对比code
        // Object code = session.getAttribute("code");

        // 从redis获取验证码
        String code = stringRedisTemplate.opsForValue().get("login:code:" + loginForm.getPhone());
        log.info("[获取的验证码是]：【{}】" , code);
        if(code == null || !code.toString().equals(loginForm.getCode())) {
            // 校验不通过
            return Result.fail("验证码错误");
        }

        // 3、校验通过，获取用户信息
        User user = query().eq("phone", loginForm.getPhone()).one();
        if(user == null) {
            //创建用户
            user = createUser(loginForm);
        }

        // 4、保存用户信息到session
        // session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        // 保存用户信息到redis
        String token = UUID.randomUUID().toString();
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        // 转换成map，这里还将他的属性值，转换成了string类型的，因为我们这个map存放的是string类型
        Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        // 两个属性都放进去
        stringRedisTemplate.opsForHash().putAll(token, map);
        // 设置过期时间
        stringRedisTemplate.expire(token, 30, TimeUnit.MINUTES);

        return Result.ok(token);
    }

    @Override
    public Result me() {
        // 直接获取用户
        UserDTO user = UserHolder.getUser();
        System.out.println(user);

        return Result.ok(user);
    }

    private User createUser(LoginFormDTO loginForm) {
        User user = new User();
        user.setPhone(loginForm.getPhone());
        user.setNickName(RandomUtil.randomNumbers(8));
        this.save(user);
        return user;
    }
}
